<template>
  <div id="container2">
  </div>
</template>

<script setup>
import * as THREE from 'three';
import {OrbitControls} from "three/addons/controls/OrbitControls.js";
import {GLTFLoader} from 'three/addons/loaders/GLTFLoader.js';

let scene = ''
let camera = ''
let renderer = ''
let controls = ''
const init = () => {
  //创建场景（需要渲染哪些物体在场景中）
  scene = new THREE.Scene();

//添加背景颜色
  scene.background = new THREE.Color(0x666666);
  // 加载gltf实例
  const loader = new GLTFLoader();
  loader.load('./liangchang.glb', function (gltf) {
    console.log("获取glb", gltf)
    scene.add(gltf.scene);
  })
  // 添加环境光
  const light = new THREE.AmbientLight(0x404040, 10);
  scene.add(light)

// 添加平行光
  const directionalLight = new THREE.DirectionalLight(0xffffff, 5);
  directionalLight.position.set(11.2, 11.2, 7.4)
  scene.add(directionalLight)


}

// 初始化相机
const initCamera = () => {
  // 相机夹角
  const fov = 15
  // 物体宽度
  const distance = window.innerWidth / 2 / Math.tan(Math.PI / 12)
  camera = new THREE.PerspectiveCamera();
  camera.position.z = 9;
  camera.position.y = -3;
  camera.position.x = 10;
  // camera.lookAt(new THREE.Vector3(200, 0, 0))
}

// 添加相机
// const add

const rendererActive=()=>{
  //创建一个渲染器
  renderer = new THREE.WebGLRenderer()
// 调整渲染器大小
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.render(scene, camera);
}

// 添加控制器
const controlsActive =  ()=>{
  // 添加轨道控制器
  controls = new OrbitControls(camera, renderer.domElement);
// 对控制器轨道改变时监听
// controls.addEventListener('change', () => {
//   console.log("触发改变")
// })
  //阻尼
  controls.enableDamping = true;

  controls.dampingFactor = 0.2;
  controls.enabled=true
// 自动旋转
//   controls.autoRotate = true;
//   controls.autoRotateSpeed = 0.5;

}

// 不断刷新
function animate() {
  // 传入回到函数
  requestAnimationFrame(animate);
  // 轨道控制器更新 (移动相机)
  controls.update()
  // 不断重绘
  renderer.render(scene, camera);
}


onMounted(() => {
  init()
  initCamera()
  rendererActive()
  controlsActive()
  document.querySelector("#container2").appendChild(renderer.domElement);
  animate()
})
</script>


<style scoped>

</style>
